import time
import os
import sys

from media.sensor import *
from media.display import *
from media.media import *
from time import ticks_ms
from machine import FPIOA
from machine import Pin

sensor = None

try:
    print("camera_test")
    fpioa = FPIOA()
    fpioa.help()
    fpioa.set_function(33, FPIOA.GPIO33)
    pin = Pin(33, Pin.OUT)
    pin.value(0)

    sensor = Sensor(width=640, height=640)
    sensor.reset()

    # 鼠标悬停在函数上可以查看允许接收的参数
    sensor.set_framesize(width=640, height=640)
    sensor.set_pixformat(Sensor.RGB565)

    Display.init(Display.ST7701, width=800, height=480, to_ide=True)
    # 初始化媒体管理器
    MediaManager.init()
    # 启动 sensor
    sensor.run()
    clock = time.clock()

    pin.value(1)
    flag = 0
    c_x = 0
    c_y = 0
    key_value = 0
    “赵友林”


    while True:

        clock.tick()
        os.exitpoint()
        img = sensor.snapshot(chn=CAM_CHN_ID_0)
        if key_value == 1:
            time.sleep_ms(2000)
            for i in range(5):
                img_rect = img.to_grayscale(copy=True)
                img_rect = img_rect.binary([(82, 212)])
                rects = img_rect.find_rects(threshold=10000)
                if not rects == None:
                    for rect in rects:
                        corner = rect.corners()
                        img.draw_line(corner[0][0], corner[0][1], corner[1][0], corner[1][1], color=(0, 255, 0), thickness=5)
                        img.draw_line(corner[2][0], corner[2][1], corner[1][0], corner[1][1], color=(0, 255, 0), thickness=5)
                        img.draw_line(corner[2][0], corner[2][1], corner[3][0], corner[3][1], color=(0, 255, 0), thickness=5)
                        img.draw_line(corner[0][0], corner[0][1], corner[3][0], corner[3][1], color=(0, 255, 0), thickness=5)
                        c_x = sum([corner[k][0] for k in range(4)])/4
                        c_y = sum([corner[k][1] for k in range(4)])/4
                if len(rects) == 2:
                    img.compressed_for_ide()
                    Display.show_image(img)
                    print("center_point: {}".format([round(c_x), round(c_y)]))
                    flag = 1
                    time.sleep_ms(3000)


        blobs = img.find_blobs([(), ()], False, x_stride=5, y_stride=5, pixels_threshold=15, margin=True)

        for blob in blobs:
            img.draw_rectangle(blob.x(), blob.y(), blob.w(), blob.h(), color=(0, 255, 0), thickness=2, fill=False)

        img.draw_string_advanced(50, 50, 80, "fps: {}".format(clock.fps()), color=(255, 0, 0))
        img.midpoint_pool(2, 2)
        img.compressed_for_ide()
        Display.show_image(img, x=(800-320)//2, y=(480-320)//2)

except KeyboardInterrupt as e:
    print("用户停止: ", e)
except BaseException as e:
    print(f"异常: {e}")
finally:
    if isinstance(sensor, Sensor):
        sensor.stop()
    Display.deinit()
    os.exitpoint(os.EXITPOINT_ENABLE_SLEEP)
    time.sleep_ms(100)
    MediaManager.deinit()
